#include <iostream>
#include "Serveclient.h"
#include "Log.h"
#include "Comm.h"
#include "commline.h"
#include "SR.h"
#include <cstring>
#include <unistd.h>
#include <thread>
#include <sys/epoll.h>

using std::cout;
using std::endl;
using namespace LogMudule;
static const int MAX_LENTH = 1024;

int main(int argc, char *argv[])
{
    // 接受参数
    bool isLR;

    if (!paraseArgs(argc, argv, isLR, uname, password))
    {
        std::cout << "Usage:./client_tcpuanme,password" << std::endl;
        Die(USAGE_ERR);
    }
    const std::string serve_ip = SERVER_IP;
    const int serve_port = SERVER_PORT;
    // 创建socket
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::ERROR) << "create socket error";
        Die(SOCKET_ERR);
    }
    // 初始化
    struct sockaddr_in serve;
    bzero(&serve, sizeof(serve));
    serve.sin_family = AF_INET;
    serve.sin_port = htons(serve_port);
    serve.sin_addr.s_addr = inet_addr(serve_ip.c_str());
    int n = ::connect(sockfd, CONV(&serve), sizeof(serve));
    if (n < 0)
    {
        LOG(LogLevel::ERROR) << "connect error";
        Die(CONNECT_ERR);
    }
    Protocol pro;
    std::string req = uname + " " + password;
    if (isLR == true)
    {
        pro.be_ = Behavior::REGISTER;
        pro.len_ = req.size();
        stpncpy(pro.buf, req.c_str(), pro.len_);
        pro.buf[sizeof(pro.buf) - 1] = '\0';
        Send(sockfd, pro);
    }
    else
    {
        pro.be_ = Behavior::LOGIN;
        pro.len_ = req.size();
        stpncpy(pro.buf, req.c_str(), pro.len_);
        Send(sockfd, pro);
    }
    Protocol res = Recv(sockfd);
    // pid_t pid = fork();
    // if (pid == 0)
    // {
    //     if (fork() > 0)
    //     {
    //         exit(0);
    //     }
    //     HandInput();
    //     exit(0);
    // }
    // while (1)
    // {
    //     ::wait(nullptr);
    // }
    while (1)
    {
        HandInput();
    }
    ::close(sockfd);
    return 0;
}